﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Microsoft.Win32;
using System.Windows;
using System.Xml;
using System.Windows.Media;

namespace SHomeWorkshop.LunarMind.Commands
{
    /// <summary>
    /// 以此类为模板，制作自定义命令类
    ///     共需要修改１０处！！！
    /// ==============================
    /// 
    /// 插入同级标题命令。
    /// ★①，修改类名。
    /// </summary>
    public static class InsertSameLevelTitleCommand
    {
        private static RoutedUICommand routedUICmd;//创建私有字段

        public static RoutedUICommand RoutedUICmd//创建只读静态属性
        {
            get { return routedUICmd; }
        }

        /// <summary>
        /// ★②，修改静态构造方法名。
        /// </summary>
        static InsertSameLevelTitleCommand()//类型构造器
        {
            //★③，修改两个字符串参数名。★④以及第三个参数的类型名。
            routedUICmd = new RoutedUICommand(
                "InsertSameLevelTitleCommand",
                "InsertSameLevelTitleCommand",
                typeof(InsertSameLevelTitleCommand),//创建RoutedUICommand对象
                null/*new InputGestureCollection() 
                { 
                    //★⑤，修改此处两个参数，以便挂接快捷键。
                     * 横向列表时，如果碰到subRoot更改快捷键行为
                    new KeyGesture(Key.Enter,ModifierKeys.Shift,"Shift+Enter"),
                    new KeyGesture(Key.Tab,ModifierKeys.Shift,"Shift+Tab"),
                }*/);

            cmdBinding.Command = routedUICmd;
            cmdBinding.CanExecute += new CanExecuteRoutedEventHandler(cmdBinding_CanExecute);
            cmdBinding.Executed += new ExecutedRoutedEventHandler(cmdBinding_Executed);
        }

        private static CommandBinding cmdBinding = new CommandBinding();

        public static CommandBinding CmdBinding
        {
            get { return cmdBinding; }
        }

        static void cmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //★⑦，修改此方法的实现。

            InsertSameLevelTitle();
        }

        /// <summary>
        /// ★此方法并非自定义命令类必须的方法。
        /// </summary>
        /// <returns></returns>
        public static bool InsertSameLevelTitle(string innerText = null, ModifingItem mi = null)
        {
            if (Globals.MainWindow.SelectedTitlesList == null) return false;

            if (Globals.MainWindow.SelectedTitlesList.Count <= 0)
            {
                if (Globals.MainWindow.SelectedTitleImage != null)
                {
                    Globals.MainWindow.SelectedTitleImage.MasterTitle.SelectOnlySelf();
                }
                else
                {
                    Globals.MainWindow.RootTitle.SelectOnlySelf();
                }
            }

            Title baseTitle = Globals.MainWindow.MainSelectedTitle;

            if (baseTitle != null && baseTitle.IsFixed)
            {
                MessageBox.Show("不能为FixedTitle添加同级或下级标题。",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (baseTitle == Globals.MainWindow.RootTitle)
            {
                return Commands.InsertLowerLevelTitleCommand.InsertLowerLevelTitle(innerText);//根标题只有下级。
            }

            XmlNode tileSetNode = Globals.MainWindow.MainXmlDocument.DocumentElement.SelectSingleNode("TitleSet");
            if (tileSetNode == null)
            {
                MessageBox.Show("当前文档的后台Xml数据中未找到“TitleSet”节点。",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            bool shouldDo = false;
            if (mi == null)
            {
                mi = new ModifingItem()
                {
                    IsNeedRefreshTitleAndLinesLocation = true,
                    ModifingName = "插入同级标题"
                };
                shouldDo = true;
            }

            //与插入下级不同，这里需要先空出一个索引。
            Title higherTitle = Globals.MainWindow.GetTitleByID(baseTitle.HigherLevelTitleID);

            if (higherTitle == null)
            {
                MessageBox.Show("未找到上级标题，无法在此标题下插入新标题。", Globals.AppName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (higherTitle.LowerLevelTitles.Count > 0 &&
                higherTitle.LowerLevelTitles.Contains(baseTitle))
            {
                foreach (Title t in higherTitle.LowerLevelTitles)
                {
                    if (t.Index > baseTitle.Index)
                    {
                        Action actIndex = new Action(t.ID, -1, t.GetType().Name,
                            "Index", t.Index.ToString(), (t.Index + 1).ToString());
                        t.Index += 1;
                        mi.Add(actIndex);
                    }
                }
            }

            XmlNode newNode;

            Title higher = baseTitle.GetHigherLvelTitle();
            if (higher != null && higher.IsRootTitle)
            {
                var docBack = Globals.MainWindow.mainCanvas.Background;
                if (docBack is ImageBrush)
                {
                    // 只支持一种：浅花文背景色，应返回深色分支线色。
                    newNode = tileSetNode.AppendXml(Properties.Resources.SubRootDarkTitleOutXml);  //一级标题，默认字号大些，文字默认为白色。
                }
                else
                {
                    var bsh = docBack as SolidColorBrush;
                    if (bsh == null || Globals.IsLightColor(bsh.Color))
                    {
                        newNode = tileSetNode.AppendXml(Properties.Resources.SubRootDarkTitleOutXml);  //一级标题，默认字号大些，文字默认为白色。
                    }
                    else
                    {
                        newNode = tileSetNode.AppendXml(Properties.Resources.SubRootLightTitleOutXml);  //一级标题，默认字号大些，文字默认为白色。
                    }
                }
            }
            else
            {
                var docBack = Globals.MainWindow.mainCanvas.Background;
                if (docBack is ImageBrush)
                {
                    // 只支持一种：浅花文背景色，应返回深色分支线色。
                    newNode = tileSetNode.AppendXml(Properties.Resources.TitleDarkOutXml);
                }
                else
                {
                    var bsh = docBack as SolidColorBrush;
                    if (bsh == null || Globals.IsLightColor(bsh.Color))
                    {
                        newNode = tileSetNode.AppendXml(Properties.Resources.TitleDarkOutXml);
                    }
                    else
                    {
                        newNode = tileSetNode.AppendXml(Properties.Resources.TitleLightOutXml);
                    }
                }                
            }

            if (string.IsNullOrWhiteSpace(innerText) == false)
            {
                var textSetNode = newNode.SelectSingleNode("TextSet");
                if (textSetNode != null)
                {
                    textSetNode.SelectSingleNode("Text").InnerText = innerText; //选中第一个“Text”节点并将值传递过来。
                }
            }

            Title newTitle = new Title(Globals.MainWindow);

            if (higherTitle == Globals.MainWindow.RootTitle)
            {
                newTitle.Direction = baseTitle.Direction;
            }

            newTitle.SetXmlData(newNode);
            newTitle.Index = baseTitle.Index + 1;
            newTitle.HigherLevelTitleID = higherTitle.ID;//必须在这之后再Build()，否则会被当作Roottitle。

            newTitle.BuildTitle();

            newTitle.Direction = baseTitle.Direction;
            newTitle.RefreshMainTextBlockToolTip();

            if (higher != null && higher.IsRootTitle)
            {
                newTitle.TitleBackground = newTitle.RelationLineStroke;
            }
            newTitle.RefreshTitleBackground();

            Globals.MainWindow.mainCanvas.Children.Add(newTitle);

            Action actInsertNewTitle = new Action(newTitle.ID, newTitle.Index,
                newTitle.GetType().Name, "InsertTitle", null, newTitle.XmlData.OuterXml,
                ActionType.InsertTitle, baseTitle.ID);

            mi.Add(actInsertNewTitle);
            if (shouldDo) mi.OldSelectedTitleID = baseTitle.ID;
            mi.NewSelectedTitleID = newTitle.ID;

            newTitle.IsNeedSizeInvalid = true;

            if (shouldDo)
            {
                Globals.MainWindow.Do(mi);
                Globals.MainWindow.IsModified = true;

                Globals.MainWindow.RefreshAutoNumber();
                Globals.MainWindow.RefreshTitleAndLinesLocation();
            }

            newTitle.SelectOnlySelf();

            return true;
        }

        static void cmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            //★⑧，修改此方法的实现。
            if (Globals.MainWindow.SelectedTitlesList.Count > 0 ||
                Globals.MainWindow.RootTitle != null)
            {
                if (Globals.MainWindow.MainSelectedTitle != null)
                {
                    if (Globals.MainWindow.MainSelectedTitle.IsFixed)
                    {
                        e.CanExecute = false;
                        return;
                    }
                }

                e.CanExecute = true;//如果当前没有选中任何标题，则以根标题为基准标题。
            }
            else e.CanExecute = false;
        }
    }
}
